#coding=utf-8

"""python2的urllib[2]使用"""

import urllib
import urllib2


def send_request():
    #输入自定义查询的关键字,python2的输入是raw_input
    keyword = raw_input("请输入需要查询的关键字")
    #固定的url地址
    base_url = "https://www.baidu.com/s?"
    
    #-----------字典转查询字符串-------
    #构建查询字典,这里的键名需要去百度地址上测试找到对应的键名
    query_dict = {"wd": keyword}
    #通过urlencode方法,按url编码转换构建查询字符串,从而能被web服务器接受
    query_str = urllib.urlencode(query_dict)

    """
    #通过urllib.unquote()方法,把url编码字符串,转换回原先字符串
    print(urllib.unquote(query_str))
    """

    #构建完整的url地址
    full_url = base_url + query_str
    #----------请求------------------
    headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"}
    #构建请求对象,此时没有传入data,为GET请求
    request = urllib2.Request(full_url, headers=headers)
    #请求
    response  = urllib2.urlopen(request)
    #响应
    return response.read()


if __name__ == '__main__':
    html = send_request()
    with open("baidu.html", "w") as f:
        f.write(html)

